// pages/bluetooth/bluetooth.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    status: false,
    isInit: false,
    canUse: false,
    devices:[],
    devicesName: [],
    Ctrler: '',
    ConnectedDeviceId: '',
    ConnectedServiceID: '0000FFE0-0000-1000-8000-00805F9B34FB',
    ConnectedCharacterID: '0000FFE1-0000-1000-8000-00805F9B34FB',
    send_msg:""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  ConnectCtrler: function(){
    var that = this;  

    // 初始化蓝牙适配器
    wx.openBluetoothAdapter({
      success: function (res) {
        console.log('初始化蓝牙适配器成功')
        that.setData({
          isInit : true
        })
      },
      fail: function (res) {
        console.log('请打开蓝牙和定位功能')
        wx.showToast({
          title: '蓝牙初始化失败',
          icon: 'error',
        })
        that.setData({
          isInit : false
        })
        return
      }
    })  

    // 检测蓝牙是否可用
    wx.getBluetoothAdapterState({
      success: function (res) {
        that.setData({
          canUse: true
        })
        console.log("\n蓝牙是否可用："+ that.data.canUse);
      },
      fail: function (res) { 
        that.setData({
          canUse: false
        })
        console.log("\n蓝牙是否可用："+ that.data.canUse);
        return
      }     
    })  
    
      // 开始搜索
    wx.startBluetoothDevicesDiscovery({
      // 如果填写了此UUID，那么只会搜索出含有这个UUID的设备，建议一开始先不填写或者注释掉这一句
      services: [that.data.ConnectedServiceID], 
      success: function (res) {
        // 获取搜索到的设备
        wx.getBluetoothDevices({
          success: function (res) {
            that.setData({
              devices: res.devices
            })
            console.log('设备信息：\n' + JSON.stringify(res.devices)+"\n")

            // 设备为空的提示
            if(that.data.devices.length == 0){
              wx.showToast({
                title: '无可用控制器',
                icon: 'error',         
              })
            }
            // 设备不为空,则设置ID号
            else{
              for(var i = 0; that.data.devices[i]; i++){
                that.data.devicesName[i] = that.data.devices[i].name;
              }
            }

            // 连接控制器
            wx.showActionSheet({
              itemList: that.data.devicesName,
              success:function(res){

                var index = res.tapIndex;
                // 连接
                wx.createBLEConnection({
                  deviceId:  that.data.devices[res.tapIndex].deviceId,
                  success: function (res) {
                    console.log('调试信息：' + res.errMsg);
                    wx.showToast({
                      title: '连接成功',
                      icon: 'success',
                    })
                    that.setData({
                      status: true,
                      ConnectedDeviceId: that.data.devices[index].deviceId,
                      Ctrler: that.data.devicesName[index]
                    })
                  },
                  fail: function () {
                    console.log("连接失败");
                    wx.showToast({
                      title: '连接失败',
                      icon: 'error',
                    })
                    that.setData({
                      status: false,
                      ConnectedDeviceId: '',
                      Ctrler: ''
                    })
                  },       
                })
              },
              fail: function(res) {
                console.log(res.errMsg)
                }
            }); 
          }
        })     
      }
    })       
  },

  // 关闭控制器
  CloseCtrler:function(){
    var that = this;
    wx.closeBLEConnection({
      deviceId: that.data.ConnectedDeviceId,
      success: function (res) {
        that.setData({
          ConnectedDeviceId: "",
          status: false
        })
        console.log('断开蓝牙设备成功：' + res.errMsg)
        wx.showToast({
          title: '断开连接成功',
        })
      },
      fail:function(res){
        console.log('断开蓝牙设备失败：' + res.errMsg)
        wx.showToast({
          title: '断开连接失败',
          icon: 'error'
        })
      }
    })  
  },

  // 发送数据
  SendData:function(){
    var that = this
    that.data.send_msg = "help"
    var msg = that.data.send_msg
    // 转字符串进行发送
    var buf = new ArrayBuffer(msg.length * 2); // 每个字符占用2个字节
    var bufView = new Uint16Array(buf);
    for (var i = 0, strLen = msg.length; i < strLen; i++) {
      bufView[i] = msg.charCodeAt(i);
    }
    console.log('要发送的信息是：'+ msg)
    console.log(msg)
    
    // 发送数据
    wx.writeBLECharacteristicValue({
      deviceId: that.data.ConnectedDeviceId,
      serviceId: that.data.ConnectedServiceID,
      characteristicId: that.data.ConnectedCharacterID,
      // 这里的value是ArrayBuffer类型
      value: bufView.buffer,
      success: function (res) {
        console.log('写入成功', res.errMsg)
        wx.showToast({
          title: '写入成功',
        })
      },
      fail(res){
        console.log(res.errCode)
        console.log('写入失败', res.errMsg)    
        wx.showToast({
          title: '写入失败',
          icon: 'error'
        })
      }
    })    
  }
})



